package core.scan;

import core.annotation.AfterStart;
import core.annotation.BeforeStart;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

@Slf4j
public class ScanClass extends AbstractScanPackage {

    private static ScanClass scanClass;

    public static synchronized ScanClass getScanClass(){
        if(scanClass == null){
            scanClass = new ScanClass();
        }
        return scanClass;
    }

    private static final String superClassName = "core.annotation.StartHandle";

    public String subClassPath(String filePath,String packagePath){
        filePath = filePath.replace(File.separator,".");
        int lastPackageIndex = filePath.lastIndexOf(packagePath);
        String lastClassName = filePath.substring(lastPackageIndex).replace(File.separator,".");
        return lastClassName.substring(0,lastClassName.length() - 6);
    }

    public Class scanAfterClass(String filePath,String packagePath) throws ClassNotFoundException, NoSuchFieldException {
        String classPath = subClassPath(filePath,packagePath);
        Class loadClass = Class.forName(classPath);
        AfterStart after = (AfterStart) loadClass.getAnnotation(AfterStart.class);
        if(after == null){
            return null;
        }
        for(Class c : loadClass.getInterfaces()){
            if(c.getName().equals(superClassName)){
                return loadClass;
            }
        }
        return null;
    }

    public Class scanBeforeClass(String filePath,String packagePath) throws ClassNotFoundException {
        String classPath = subClassPath(filePath,packagePath);
        Class loadClass = Class.forName(classPath);
        BeforeStart before = (BeforeStart) loadClass.getAnnotation(BeforeStart.class);
        if(before == null){
            return null;
        }
        for(Class c : loadClass.getInterfaces()){
            if(c.getName().equals(superClassName)){
                return loadClass;
            }
        }
        return null;
    }
}
